#!/usr/bin/env bash

# CleanLatex v1.0
# by Bill Garrison
# bill@cs.pitt.edu
# Licensed under GPLv3

usage()
{
  echo "Usage: `basename $0` [-p] latex_file"
  exit -1
}

parse_flags()
{
  while getopts "p" flag; do
    if [ $flag == "?" ]; then
      usage
    elif [ $flag == "p" ]; then
      pdf=1
    fi
  done

  if [ $# -ne $OPTIND ]; then
    usage
  fi

  shift $((OPTIND-1))
  thefile=${1%\.tex}
}

find_pstopdf()
{
  if [ `command -v pstopdf` ]; then
    pstopdf=pstopdf
  elif [ `command -v ps2pdf` ]; then
    pstopdf=ps2pdf
  else
    echo "No ps-to-pdf utility found."
    exit -1
  fi
}

parse_flags $@

# Ensure the argument is a .tex file and exists.
if [ ! -f $thefile.tex ]; then
  echo "Can't find ${thefile}.tex"
  usage
fi

if [ $pdf ]; then
  # Compile the TeX directly to PDF
  pdflatex $thefile
  # Ensure pdflatex returned correctly
  if [ $? -ne 0 ]; then
    exit -1
  fi
  # Run bibtex to create bibliography
  bibtex $thefile
  # Compile again to fix reference database
  pdflatex $thefile
  # Run bibtex again to create references
  bibtex $thefile
  # Compile again to fix references
  pdflatex $thefile
  # Remove leftovers from latex
  rm $thefile.aux $thefile.log $thefile.out
  # Remove leftovers from bibtex
  rm $thefile.bbl $thefile.blg
else
  # Compile the TeX to DVI
  latex $thefile
  # Ensure latex returned correctly
  if [ $? -ne 0 ]; then
    exit -1
  fi
  # Run bibtex to create bibliography
  bibtex $thefile
  # Compile again to fix reference database
  latex $thefile
  # Run bibtex again to create references
  bibtex $thefile
  # Compile again to fix references
  latex $thefile
  # Remove leftovers from latex
  rm $thefile.aux $thefile.log $thefile.out
  # Remove leftovers from bibtex
  rm $thefile.bbl $thefile.blg
  # Convert the DVI to postscript
  dvips $thefile -o
  # Remove the DVI
  rm $thefile.dvi
  # Convert the postscript to PDF
  find_pstopdf
  $pstopdf $thefile.ps
  # Remove the postscript
  rm $thefile.ps
fi
